package com.ipfsemc.ipfsemc.wx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

@Component
public class SignUtil {

    @Autowired
    private EncryptTool encryptTool;


    /**
     * 校验签名
     *
     * @param signature 签名
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @return 布尔值
     */
    public boolean checkSignature(String signature, String timestamp, String nonce) {
        String checktext = null;
        if (null != signature) {
            //对ToKen,timestamp,nonce 按字典排序
            String[] paramArr = new String[]{"weixin4j", timestamp, nonce};
            Arrays.sort(paramArr);
            //将排序后的结果拼成一个字符串
            String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);
            checktext = encryptTool.encryption(content, encryptTool.SHA1);
        }
        //将加密后的字符串与signature进行对比
        System.out.println("checktext:" + checktext);
        System.out.println("signature:" + signature);
        return checktext != null ? checktext.equals(signature) : false;
    }

}
